﻿namespace Guia.Elements.PatternServants
{
    using System.Windows.Automation;
    using Guia.Core;

    /// <summary>
    /// Represents the implementation for the Toggle-Pattern.
    /// </summary>
    public class ToggleImpl : AbstractPatternServant, IToggle
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ToggleImpl"/> class.
        /// </summary>
        /// <param name="automationElement">The automation element.</param>
        public ToggleImpl(UiElement automationElement)
            : base(automationElement)
        {
        }

        #region IToggle Members

        /// <summary>
        /// Gets a value indicating whether the state is off or not.
        /// </summary>
        public bool IsOff
        {
            get
            {
                return this.GetTogglePattern().Current.ToggleState == ToggleState.Off;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the state is on or not.
        /// </summary>
        public bool IsOn
        {
            get
            {
                return this.GetTogglePattern().Current.ToggleState == ToggleState.On;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the state is indeterminate or not.
        /// </summary>
        public bool IsIndeterminate
        {
            get
            {
                return this.GetTogglePattern().Current.ToggleState == ToggleState.Indeterminate;
            }
        }

        /// <summary>
        /// Toggles the UiElement.
        /// </summary>
        /// <exception cref="OperationNotSupportedException">This exception is thrown when the toggle-action is not supported in the current context (e.g. the UiElement is disabled).</exception>
        public void Toggle()
        {
            try
            {
                this.GetTogglePattern().Toggle();
            }
            catch (ElementNotEnabledException)
            {
                throw new OperationNotSupportedException("The control is not enabled");
            }
        }

        #endregion

        /// <summary>
        /// Gets the TogglePattern.
        /// </summary>
        /// <returns>
        /// The TogglePattern
        /// </returns>
        private TogglePattern GetTogglePattern()
        {
            return this.UiElement.GetPattern<TogglePattern>();
        }
    }
}
